import Vue from 'vue'
import VueRouter from 'vue-router'
import {Message} from 'element-ui'

Vue.use(VueRouter)

const routes = [
  {
    path: '/',
    name: 'login',
    require:'/login',
    component: () => import(/* webpackChunkName: "login" */ '../views/login/index.vue')
  },
  {
    path: '/layout',
    name: 'layout',
    meta:{
      name:'首页'
    },
    component: () => import(/* webpackChunkName: "layout" */ '../views/layout/index.vue'),
    require:'/layout/recommend',
    children:[
      {
        path:'/layout/home',
        name:'home',
        meta:{
          name:'首页',
          icon:'el-icon-chat-dot-round',
        },
        component: () => import(/* webpackChunkName: "home" */ '../views/home/index.vue')
      },
      {
        path:'/layout/recommend',
        name:'recommend',
        meta:{
          name:'推荐',
          icon:'el-icon-pie-chart',
        },
        component: () => import(/* webpackChunkName: "home" */ '../views/recommend/index.vue')
      },
      {
        path:'/layout/interspace',
        name:'interspace',
        meta:{
          name:'空间',
          icon:'el-icon-bangzhu',
        },
        component: () => import(/* webpackChunkName: "home" */ '../views/interspace/index.vue')
      },
      {
        path:'/layout/lbt',
        name:'lbt',
        meta:{
          name:'轮播图',
          icon:'el-icon-bangzhu',
        },
        component: () => import(/* webpackChunkName: "home" */ '../views/lbt/index.vue')
      },
      {
        path:'/layout/about',
        name:'about',
        meta:{
          name:'关于',
          icon:'el-icon-user',
        },
        component: () => import(/* webpackChunkName: "about" */ '../views/about/index.vue')
      }
    ]
  }
]

//添加以下代码
const originalPush = VueRouter.prototype.push
VueRouter.prototype.push = function push(location) {
  return originalPush.call(this, location).catch(err => err)
}
const router = new VueRouter({
  mode: 'history',
  base: process.env.BASE_URL,
  routes
})

//添加守卫
router.beforeEach((to,from,next)=>{
  //如果是访问登录，直接放行
  if(to.path === "/"){
    next();
  }else{
    //查看是否登陆过
    if(localStorage.getItem("token")){
      next();
    }else{
      Message.warning('请先登录')
      next("/");
    }
  }
})

export default router
